package com.lindenvalley.ch;

import java.text.ParseException;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextSwitcher;
import android.widget.TextView;

import com.lindenvalley.ch.adapters.TasksArrayAdapter;
import com.lindenvalley.ch.content.Task;
import com.lindenvalley.ch.content.Week;

public class TagesberichtActivity extends AbstractHomeActivity{
	
	private int bigFontDayActivePixel;
	private int smallFont;
	private int selectedDayActive;
	protected AbsoluteSizeSpan bigSizeSpan, smallSizeSpan;
	private final static int[] days = new int[] { R.id.homeButtonDie,
		R.id.homeButtonMit, R.id.homeButtonDon, R.id.homeButtonMon,
		R.id.homeButtonFre, R.id.homeButtonSam, R.id.homeButtonSon };
	private TasksArrayAdapter adapter;
	public static final String EDIT_INTENT = "editIntent";
	public static final String WEEKS_INTENT_DATA = "weeksIntentData";
	public static final String CUR_WEEK_INTENT_DATA = "weekIntentData";
	public static final String CUR_TASK_INTENT_DATA = "taskIntentData";
	public static final String CUR_DAY_INTENT_DATA = "dayIntentData";
	public static final String RESULT_WEEK_DATA = "whichWeekIntentData";
	public static final String CREATE_EVERYWHERE_INTENT_DATA = "createEverywhereIntentData";


	
	public void onCreate(Bundle bundle){
		super.onCreate(bundle);
		setContentView(R.layout.tagesbericht);
		getResources().getStringArray(R.array.daysName);
		bigFontDayActivePixel = getResources().getDimensionPixelSize(R.dimen.bigFontDayActive);
		getResources().getDimensionPixelSize(R.dimen.bigFontDayInactive);		
		smallFont = getResources().getDimensionPixelSize(R.dimen.smallFontDay);
		getResources().getDimensionPixelSize(R.dimen.paddingTopDay);
		bigSizeSpan = new AbsoluteSizeSpan(bigFontDayActivePixel);
		smallSizeSpan = new AbsoluteSizeSpan(smallFont);
		initLayout();
	}
	
	/* (non-Javadoc)
	 * @see com.lindenvalley.ch.AbstractHomeActivity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode == Activity.RESULT_OK && requestCode == 1) {
			int which = data.getIntExtra(RESULT_WEEK_DATA, currentWeekIndex);
			setCurrentTaskOfWeek(weeks.getReverseWeek(which));
		} else {
			super.onActivityResult(requestCode, resultCode, data);
		}
		
	}

	public void initLayout(){
		
		super.initLayout();
		
		MyTouchDayListener touchDayListener = new MyTouchDayListener();
		
		TextSwitcher ts;
		TextView tv;
		int day;
		Typeface typeface = Typeface.createFromAsset(getAssets(), "HelveticaNeueCondensedBold.ttf");
		int dayOfWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);		
		
		ListView lv = (ListView) findViewById(R.id.listView1);
		adapter = new TasksArrayAdapter(this, R.layout.tagesbericht_row, null);
		lv.setAdapter(adapter);
		lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				int taskId = adapter.getItem(position).getTaskId();
				startEditActivity(taskId, false);				
				
			}
			
		});
		
		for (int i = 0; i<days.length; i++){
			day = days[i];
			ts = (TextSwitcher) findViewById(day);
			tv = (TextView) ts.getChildAt(1);
			tv.setTypeface(typeface);
			tv =  (TextView) ts.getChildAt(0);
			tv.setTypeface(typeface);			
			ts.setOnTouchListener(touchDayListener);
			int dayTag = Integer.parseInt(ts.getTag().toString());
			if (dayTag == dayOfWeek)
				setupActiveDay(day);
		}
	}
	

	private void setupActiveDay(int id){
				
		TextSwitcher ts = (TextSwitcher) findViewById(id);
		try{
			currentDayOfWeek = Integer.parseInt(ts.getTag().toString());
			if (currentWeek != null && !currentWeek.isEmpty()){
				adapter.setTasks(currentWeek.getTaskForDay(currentDayOfWeek));
			} else {
				adapter.setTasks(null);
			}
		} catch (NumberFormatException ex){
			ex.printStackTrace();
			
		} catch (NullPointerException ex){
			ex.printStackTrace();
		}
		if (ts != null){
			selectedDayActive = id;
			ts.setText(setupTextActiveDay(((TextView)ts.getChildAt(0)).getText().toString()));
//			if (currentWeek != null){
//				
//			} else {
//				ts.showNext();
//			}
			
		}
		
	}
	
	private SpannableString setupTextActiveDay(String dayName){
		SpannableString str = null;
		if (currentWeek != null){
			calendar.setTimeInMillis(currentWeek.getStartDate() * 1000L);
		} else{
			calendar.setTimeInMillis(System.currentTimeMillis());
		}
			
		calendar.set(Calendar.DAY_OF_WEEK, currentDayOfWeek);
		String currentDate = dateFormat.format(calendar.getTime());
//			String dayName = getResources().getStringArray(R.array.daysName)[currentDayOfWeek-1];
		str = formatStringToView(dayName + "\n" + currentDate);
		return  str;
	}
	
	protected SpannableString formatStringToView(CharSequence text) {
		SpannableString spanString = null;
		if (text != null) {			
			spanString = new SpannableString(text);
			 spanString.setSpan(bigSizeSpan, 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			 spanString.setSpan(smallSizeSpan, 3, spanString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
		return spanString;
	}
	
	private void setupDayIcons(){
		for (int day: days){
			TextSwitcher ts = (TextSwitcher) findViewById(day);
			TextView tv = (TextView) ts.getChildAt(0);
			int dayTag = Integer.parseInt(ts.getTag().toString());
			List<Task> tasksForDay = currentWeek.getTaskForDay(dayTag);
			if (currentWeek != null && tasksForDay != null && !tasksForDay.isEmpty()){				
				tv.setCompoundDrawablesWithIntrinsicBounds(null, null, null,getResources().getDrawable(R.drawable.icon_day_check));
			} else {
				tv.setCompoundDrawablesWithIntrinsicBounds(null, null, null,null);
			}
			
			//TODO Для активного лейбла перерисовать нужную текущую дату
			if (ts.getCurrentView() == ts.getChildAt(1)){
				TextView tv1= (TextView)ts.getChildAt(1);
				tv1.setText(setupTextActiveDay(((TextView)ts.getChildAt(0)).getText().toString()));
				
			}
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	
	private class MyTouchDayListener implements OnTouchListener{

		public MyTouchDayListener() {
			super();			
		}

		@Override
		public boolean onTouch(View v, MotionEvent event) {

			int id = v.getId();
			if (event.getAction() == MotionEvent.ACTION_DOWN){				
				switch (id) {
				case R.id.homeButtonMon:
				case R.id.homeButtonDie:
				case R.id.homeButtonMit:
				case R.id.homeButtonDon:
				case R.id.homeButtonFre:
				case R.id.homeButtonSam:
				case R.id.homeButtonSon:
					if (selectedDayActive != id){
						TextSwitcher prevTv = (TextSwitcher)  TagesberichtActivity.this.findViewById(selectedDayActive);
						setupActiveDay(id);
//						getTasks();
						if (prevTv != null){
							prevTv.showNext();
						}												
					}
				break;
				}
			}
			return true;
		}
		
	}

	@Override
	public synchronized void setCurrentTaskOfWeek(Week week) {
		currentWeek = week;
		currentWeekIndex = weeks.getWeekIndexByDate(currentWeek.getStartDate());
		if (adapter != null){
			adapter.setTasks(currentWeek.getTaskForDay(currentDayOfWeek));
		}
		setSearchViewText();
		setupDayIcons();
	}
	
	public void onClickTack (View v){
		
	}
}
